package com.hibernate.bigtype.mains;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.sql.Blob;
import java.sql.Clob;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.hibernate.bigtype.dto.User;

public class MainDriver {

	private SessionFactory factory;

	private Session session;

	private Transaction transaction;

	@Before
	public void init() {
		Configuration cfg = new Configuration().configure();

		ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
				.buildServiceRegistry();
		factory = cfg.buildSessionFactory(registry);
	}

	@After
	public void destory() {
		factory.close();
	}

	private void openSession() {
		session = factory.openSession();
		transaction = session.beginTransaction();
	}

	private void closeSession() {
		transaction.commit();
		session.close();
	}

	@Test
	public void saveBlob() throws Exception{

		openSession();

		User u = new User();
		u.setName("liuxing");
		
		//创建Blob字段
		FileInputStream is = new FileInputStream("aaa.jpg");
		Blob blob = Hibernate.getLobCreator(session).createBlob(is,is.available());
		u.setImage(blob);
		
		//创建Clob
		FileInputStream in = new FileInputStream("des.txt");
		InputStreamReader ir = new InputStreamReader(in);
		Clob clob = Hibernate.getLobCreator(session).createClob(ir,in.available());
		u.setDesc(clob);
		
		session.save(u);
		closeSession();
	}
	
	@Test
	public void getBlob() throws Exception {

		openSession();
		User u = (User) session.get(User.class, 3);
		
		//获取Blob，并且把数据获取出来
		Blob image = u.getImage();
		InputStream is = image.getBinaryStream();
		OutputStream os = new FileOutputStream("bbb.jpg");
		byte[] buf = new byte[1024];
		while(is.read(buf) != -1){
			os.write(buf);
		}
		
		//获取Clob
		Reader descClob = u.getDesc().getCharacterStream();
		char[] chars = new char[1024];
		StringBuffer sb = new StringBuffer();
		while(descClob.read(chars) != -1){
			sb.append(new String(chars));
		}
		System.out.println(sb.toString());
		closeSession();
	}
}
